﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class UIFollower : MonoBehaviour
{
    private Transform worldNode;
    private List<FollowerElement> uiElements;
    private List<FollowerElement> activeUIElements;

    private Vector3 lastYOffset;


    public void SetFollower(UIFollowerData data)
    {
        this.uiElements = data.uiElements;
        this.worldNode = data.worldNode;

        activeUIElements = new List<FollowerElement>();
    }

    private void UpdateAllElements()
    {
        for(int i = 0;i<uiElements.Count;i++)
        {
            var selected = uiElements[i];
            
            if(i!=0)
                lastYOffset += selected.NodeYOffset;
            else
                lastYOffset = Vector3.zero;

            selected.SetRectPosFromWorldObj(worldNode,lastYOffset);
        }
    }

    private void ClearAllList()
    {
        activeUIElements.Clear();

        for(int i = 0 ;i < uiElements.Count;i++)
        {
            var selectElement = uiElements[i];
            selectElement.DestroyRect();
        }
    }


    #region "MonoBehavior"
    void Start() 
    {
        if(uiElements == null)
        {
            Debug.LogError("UIFollower未被正确初始化！现已禁用UIFollower");
            gameObject.SetActive(false);
            return;
        }
    }

    void Update()
    {
        UpdateAllElements();
    }

    void OnDestroy() 
    {
        ClearAllList();
    }
    #endregion
}

public struct UIFollowerData
{
    public List<FollowerElement> uiElements;
    public Transform worldNode;
}